<template>
  <div class="info" v-loading="loading">
    <div class="info-title">
      <div class="left">服务详情</div>
    </div>
    <div class="info-content">
      <el-card class="left" shadow="never">
        <div class="left-top">
          <div>编号：{{ events.event_number || "" }}</div>
          <el-tag
            disable-transitions
          >{{ events.status }}
          </el-tag>
        </div>
        <div class="left-bottom-info">
          <div class="info-cus">
            <div>事件类型：</div>
            <div>{{ events.type || "" }}</div>
          </div>
          <div class="info-cus">
            <div>联系人：</div>
            <div>{{ events.contact_name || "" }}</div>
          </div>
          <div class="info-cus">
            <div>联系电话：</div>
            <div>{{ events.contact_telephone || "" }}</div>
          </div>
          <div class="info-cus">
            <div>产品编号：</div>
            <div>{{ events.product_number || "" }}</div>
          </div>
          <div class="info-cus">
            <div>故障照片：</div>
            <div style="overflow: auto;flex: 1">
<!--              <img v-for="item in events.images" :src="item.image" alt="" :key="item.id"-->
<!--                   style="width: 50px;height: 50px;margin: 0 10px;">-->
              <CustomImage v-for="item in events.images" :src="item.img_url" :key="item.id" />
            </div>
          </div>
          <div class="info-cus">
            <div>情况说明：</div>
            <div>
              {{ events.description || "" }}
            </div>
          </div>

          <div class="info-cus">
            <div>地址：</div>
            <div>
              {{ events ? events.province_name : "" }}-
              {{ events ? events.city_name : "" }}-
              {{ events ? events.county_name : "" }}
            </div>
          </div>
          <div class="info-cus">
            <div>详细地址：</div>
            <div>{{ events.address || "" }}</div>
          </div>
          <div class="info-cus">
            <div>创建方式：</div>
            <div>{{ events.created_type || "" }}</div>
          </div>
          <div class="info-cus">
            <div>创建时间：</div>
            <div>{{ events.create_time_format || "" }}</div>
          </div>
          <div style="display: flex;justify-content: center">
            <el-button type="primary" @click="maintenanceCustomer"
                       v-if=" (!(events.customer_id !== 0&&events.customer_user_id !== 0))&&isClose" >保存客户信息
            </el-button>
          </div>
        </div>
      </el-card>
      <el-card class="right" shadow="never">
        <div style="display: flex;justify-content: flex-end">
          <el-button type="primary" @click="assignEvent" v-if="isAssign">分配事件</el-button>
          <el-button type="primary" @click="addWorkTicket" v-if="isClose&&isAssign" >创建工单</el-button>
        </div>
        <el-tabs v-model="tabsActive">
          <el-tab-pane label="事件进度" name="sjjd">
            <Progress :event="events"/>
          </el-tab-pane>
          <el-tab-pane label="处理结果" name="cljg" v-if="events.status==='已完成'">
            <div class="dealResult">
              <div>描述：</div>
              <div>{{ events.receipt?events.receipt.description: "" }}</div>
            </div>

            <div class="dealResult">
              <div>现场照片：</div>
              <div style="overflow: auto;flex: 1;width: 100px;height: 100px" v-if="events.receipt">
                <!--              <img v-for="item in events.images" :src="item.image" alt="" :key="item.id"-->
                <!--                   style="width: 50px;height: 50px;margin: 0 10px;">-->
                <CustomImage :width="width" :height="height" v-for="item in events.receipt.images" :src="item.img_url" :key="item.id" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="关联工单" name="glgd" v-if="events.correlation">
            <associateWorkOrder :id="id"/>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <Appoint @certainUser="certainUser" ref="Appoint"/>

    <el-dialog
      title="请保存客户消息"
      :visible.sync="saveCustomerDiaLog"
      width="30%">
      <div style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center">
        <el-button type="primary" @click="saveNew">保存为新客户</el-button>
        <el-button type="primary" @click="saveOld">保存到老客户</el-button>
      </div>
    </el-dialog>
    <el-dialog
      destroy-on-close
      title="保存客户"
      :visible.sync="saveOldCustomer"
      :before-close="cancelSaveOldCustomer"
      width="30%">
      <div>
        <el-form ref="form" :model="form" label-width="100px" :rules="rules"
                 @submit.native.prevent>
          <el-form-item label="客户名称:" prop="customer_name">
            <el-autocomplete v-model="form.customer_name" :fetch-suggestions="querySearchAsync" class="w-full"
                             style="width: 100%"
                             clearable
                             :disabled="this.events.customer_id!==0"
                             placeholder="搜索客户" value-key="name" @select="handleSelect">
              <template slot-scope="{ item }">
                <div style="margin-bottom: 10px;">
                  <div>客户名称：{{ item.name }}</div>
                  <div>客户编号：{{ item.customer_number }}</div>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="联系人:" prop="contact_name">
            <el-autocomplete v-model="form.contact_name" :fetch-suggestions="contactQuerySearchAsync" class="w-full"
                             style="width: 100%"
                             disabled
                             placeholder="搜索联系人" value-key="name" @select="handleSelectContact">
              <template slot-scope="{ item }">
                <div style="margin-bottom: 10px;">
                  <div>联系人：{{ item.name }}</div>
                  <div>联系电话：{{ item.phone }}</div>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="联系电话:" prop="contact_phone">
            <el-input
              disabled
              v-model="form.contact_phone"
              clearable
              placeholder=""/>
          </el-form-item>
          <el-form-item label="所属区域:" prop="areas">
            <el-input
              disabled
              v-model="form.city"
              clearable
              placeholder=""/>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSaveOldCustomer">取 消</el-button>
        <el-button type="primary" @click="submitOldCustomer">确 定</el-button>
      </span>
    </el-dialog>
    <AddCustomer :data="events" :visible.sync="showEdit" ref="AddCustomer" @done="done"/>
  </div>
</template>

<script>
import Progress from './components/progress'
import Appoint from "@/views/event/event/components/Appoint/index.vue";
import AddCustomer from "@/views/event/event/components/addCustomer/index.vue";
import {removePageTab} from '@/utils/page-tab-util'
import CustomImage  from "@/components/CustomImage.vue";
import associateWorkOrder from "@/views/event/event/info/components/associateWorkOrder/index.vue";

export default {
  name: "productInfo",
  computed: {
    isAssign() {
      let flag = null
      if (this.events.status) {
        flag = this.events.status === '待分配'
      }
      return flag
    },
    isClose() {
      let flag = null
      if (this.events.status) {
        flag = this.events.status !== '已关闭'
      }
      return flag
    },
    //客户存在且客户联系人存在
    isMaintenance() {
      let flag = ''
      if (this.events.status) {
        flag = this.events.customer_id !== 0&&this.events.customer_user_id !== 0
      }
      return flag
    },

  },
  components: {
    Appoint,
    Progress,
    AddCustomer,
    CustomImage,
    associateWorkOrder
  },
  watch: {
    $route() {
      if (this.$route.path === '/event/event/info') {
        this.id = this.$route.query.id; //获取传来的参数
        this.$forceUpdate()
        this.tabsActive="sjjd"
        this.loadData()
      }
    },
  },
  data() {
    const validateCustomer_name = (rule, value, callback) => {
      if (!this.form.customer_name) {
        callback(new Error("请选择客户"))
      } else {
        callback()
      }
    }
    const validateContact_name = (rule, value, callback) => {
      if (!this.form.contact_name) {
        callback(new Error("请输入联系人名称"))
      } else {
        callback()
      }
    }
    return {
      width:'100',
      height:'100',
      rules: {
        contact_name: [
          {required: true, validator: validateContact_name, trigger: "blur"}
        ],
        customer_name: [
          {required: true, validator: validateCustomer_name, trigger: "change"}
        ],
      },
      form: {
        customer_name: '',
        contact_name: '',
        contact_phone: '',
      },
      //保存到老客户弹窗
      saveOldCustomer: false,
      //选择保存客户方式弹窗
      saveCustomerDiaLog: false,
      showEdit: false,
      id: null,
      tabsActive: "sjjd",
      loading: false,
      events: {},
      //控制联系人是否可选
      contact_nameFlag:true
    }
  },
  // created() {
  //   this.id = this.$route.query.id * 1;
  // },
  mounted() {
    this.id = this.$route.query.id * 1;
    this.loadData();
  },
  methods: {
    //添加到新客户完成
    async done() {
      await this.loadData();
      this.$forceUpdate()
      // removePageTab('/event/event/info')
      // this.$router.push({path: '/workTickets/workTickets/addWorkTicket', query: {...this.events}}).catch(err => { console.log(err) })
    },
    //选择客户
    querySearchAsync(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelect(item) {
      this.form.customer_id = item.id
      //判断联系人是否存在存在传id不存在传 name
      this.$http.get(`customers/${ item.id}/users`, {
        params: {
          page: 1,
          limit: 10
        }
      }).then((res) => {
        if(res.data.data){
          let temp = res.data.data.filter((item)=>{
            return item.phone === this.events.contact_telephone
          })
          if(temp.length!==0){
            console.log("存在该联系人")
            this.form.customer_user_id=temp[0].id

          }
        }
      });
    },
    //选择联系人
    contactQuerySearchAsync(query, cb) {
      this.$http.get(`customers/${ this.form.customer_id}/users`, {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelectContact() {
        // this.form.customer_user_id = item.id
    },
    //提交保存到老客户
    submitOldCustomer() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$http.post(`/customers/${this.form.customer_id}/user`, {...this.form,event_id:this.events.id}
          ).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              new Promise((resolve) => {
                this.loadData()
                setTimeout(() => {
                  resolve();
                }, 500);
              }).then(async () => {
                await this.loadData()
                // removePageTab('/event/event/info')
                // this.$nextTick(()=>{
                //   this.$router.push({path: '/workTickets/workTickets/addWorkTicket', query: {...this.events}}).catch(err => { console.log(err) })
                // })
              })
            } else {
              this.$message.error(res.data.msg);
            }
            this.saveOldCustomer = false
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        }
      })
    },
    //取消保存到老客户
    cancelSaveOldCustomer() {
      this.form = {
          customer_name: '',
          contact_name: '',
          contact_phone: '',
      }
      this.saveOldCustomer = false
    },
    //保存到新客户对话框
    saveNew() {
      this.$refs.AddCustomer.city = [this.events.province_id, this.events.city_id, this.events.county_id]
      this.$refs.AddCustomer.cityName = this.events.province_name + '/' + this.events.city_name + '/' + this.events.county_name
      this.$refs.AddCustomer.form.name = this.events.customer_name
      this.$refs.AddCustomer.form.address = this.events.address
      this.$refs.AddCustomer.form.contact_name = this.events.contact_name
      this.$refs.AddCustomer.form.contact_phone = this.events.contact_telephone
      this.$refs.AddCustomer.form.event_id=this.events.id
      this.saveCustomerDiaLog = false
      this.showEdit = true
    },
    //保存到已有客户
    saveOld() {
      //如果客户存在直接回显并获取联系人
      if (this.events.customer_id !== 0) {
        this.form.customer_name=this.events.customer_name
        this.form.customer_id = this.events.customer_id
      }
      if (this.events.customer_id !== 0 && this.events.customer_user_id !== 0) {
        this.form.customer_user_id = this.events.customer_user_id
      }
      this.form.contact_name = this.events.contact_name
      this.form.contact_phone = this.events.contact_telephone
      this.form.province_id = this.events.province_id.toString()
      this.form.city_id = this.events.city_id.toString()
      this.form.county_id = this.events.county_id.toString()
      this.form.address=this.events.address
      this.form.city = this.events.province_name + ' ' + this.events.city_name + ' ' + this.events.county_name
      this.saveCustomerDiaLog = false
      this.saveOldCustomer = true
    },
    //派发工单
    assignEvent() {
      if(this.isMaintenance){
        this.$refs.Appoint.visible = true;
        this.$refs.Appoint.isCollaborator = false;
      }else {
        this.maintenanceCustomer()
      }

    },
    //确定负责人
    certainUser(user) {
      this.loading=true
      this.$refs.Appoint.visible = false
      this.$http.post(`events/${this.id}/allot`, {user_id: user.id}).then((res) => {
        this.$message(res.data.msg);
        this.loading=false
        this.loadData()
        // removePageTab('/event/event/info')
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    async loadData() {
      this.loading=true
     await this.$http.get(`events/${this.id}`).then((res) => {
        this.events = {...res.data.data};
        this.id=res.data.data.id
       this.$forceUpdate()
       this.loading=false
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    //事件转工单&&维护客户信息
    maintenanceCustomer(){
      if (this.events.customer_id === 0) {
        this.saveCustomerDiaLog = true
      }
      if (this.events.customer_id !== 0 ) {
        this.saveOld()
        this.saveOldCustomer = true
      }
    },
    addWorkTicket() {
      //判断客户信息存在与否&&联系人信息和客户是否匹配
      if (this.events.customer_id !== 0 && this.events.customer_user_id !== 0) {
        removePageTab('/event/event/info')
        this.$router.push({path: '/workTickets/workTickets/addWorkTicket', query: {...this.events}}).catch(err => { console.log(err) })

      }else {
        this.saveCustomerDiaLog = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.info {
  width: 96%;
  margin: 10px auto 0;

  .info-title {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;

    .left {
      font-size: 20px;
      color: #000000;
      font-weight: 600;
    }
  }

  .info-content {
    height: 80vh;
    display: flex;
    justify-content: space-between;

    .el-card + .el-card {
      margin-top: 0;
    }

    .left {
      width: 30%;
      box-sizing: border-box;
      overflow: auto;

      .left-top {
        font-size: 14px;
        color: #000000;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;
        border-bottom: 2px solid #eeeeee;
        box-sizing: border-box;
      }

      .left-bottom-info {
        font-size: 14px;

        .info-cus {
          display: flex;
          align-items: center;
          padding: 10px 0;
        }
      }
    }

    .right {
      width: 68%;
    }
  }
}
.dealResult{
  padding: 30px;
  display: flex;
}
</style>
